package haois.module.system.service;

import com.qcloud.cos.model.PutObjectResult;
import haois.constant.Reply;
import haois.constant.ReturnState;
import haois.util.FileUpLoadUtil;
import haois.util.StrUtil;
import haois.util.sdk.CosJdk;
import haois.util.sdk.JDKFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created by RuiHaoZ on 2018/3/22 20:06
 */
@Service
public class TenCloudService {

    private Logger logger = LoggerFactory.getLogger(TenCloudService.class);


    /**
     * @param mulFile    上传的文件
     * @param nativePath 保存路径
     * @param preFix     文件名前缀
     * @param cosPath    腾讯云文件夹路径
     * @return
     */
    public Reply updatePicture(MultipartFile mulFile, String nativePath, String preFix, String cosPath) {
        String randomStr = StrUtil.getFileRandomStr(preFix);
        String randomFileName = "" + randomStr + "." + StrUtil.getFileSuffix(mulFile.getOriginalFilename());
        cosPath += randomFileName;
        String filePath = FileUpLoadUtil.upload(mulFile, nativePath, randomFileName);
        File file2 = new File(nativePath + randomFileName);
        if (file2 == null) {
            return new Reply(ReturnState.CODE_10, "文件不存在");
        }
        PutObjectResult result = this.upload(file2, cosPath);
        if (result != null) {
            String photoUrl = this.getCOSPreFixUrl() + cosPath;
            logger.info("上传到腾讯云路径为:{}", photoUrl);
            return new Reply(ReturnState.CODE_00, ReturnState.SUCCESS, photoUrl);
        } else {
            return new Reply(ReturnState.CODE_10, "上传腾讯云COS失败");
        }
    }

    public PutObjectResult upload(File cosFile, String filePath) {
        CosJdk cosJdk = JDKFactory.createCos();
        return cosJdk.upload(cosFile, filePath);
    }

    public static String getCOSPreFixUrl() {
        String COSUrl = "https://h-0-1256186138.cos.ap-guangzhou.myqcloud.com";
        return COSUrl;
    }
}


